<template>
  <div class="login">
    <!-- 导航区域 -->
    <van-nav-bar title="登录" />
    <!-- 表单区域 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="rules.phoneNum"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="loading"
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginApi } from '@/api'
export default {
  data () {
    return {
      mobile: 18943602651,
      code: 246810,
      rules: {
        phoneNum: [
          { required: true, message: '请填写手机号', trigger: 'onBlur' },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号不合法',
            trigger: 'onBlur'
          }
        ],
        code: [
          { required: true, message: '请填写验证码', trigger: 'onBlur' },
          {
            pattern: /^\d{6}$/,
            message: '验证码的长度为6位',
            trigger: 'onBlur'
          }
        ]
      },
      loading: false
    }
  },
  methods: {
    async onSubmit (data) {
      this.loading = true
      try {
        const res = await loginApi(data)
        // 登陆成功之后,将 token 保存起来
        this.$store.commit('changeToken', res.data.data)
        // 判断是否有保存的路径
        // 接收参数
        const url = this.$route.query.url
        if (url) {
          this.$router.push(url)
        } else {
          // 登陆成功之后,跳转到首页
          this.$router.push('/index')
        }
        this.$toast.success('登陆成功')
      } catch {
        this.$toast.fail('登陆失败')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style></style>
